package com.auth.config;

import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.http.HttpServletRequest;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
//https://stackoverflow.com/questions/52382902/how-to-configure-oauth2-when-authorization-server-is-also-the-resource-server
@Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("ding")
                .password(new BCryptPasswordEncoder().encode("ding"))
                .roles("admin");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //这里配置未携带token才会走该过滤器链
        http.requestMatcher(new OAuthRequestedMatcher()).authorizeRequests()
                .antMatchers(  "/favicon.ico","/ssoLogin","/login","/error"
                ,"/css/**","/js/**","/images/**"
                ).permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/login")
                .and().csrf().disable().cors().disable()

        ;
    }

    //https://stackoverflow.com/questions/24085620/oauth2-spring-security-oauth2authenticationprocessingfilter-not-working
    private static class OAuthRequestedMatcher implements RequestMatcher {
        public boolean matches(HttpServletRequest request) {
            String auth = request.getHeader("Authorization");
            boolean haveOauth2Token = (auth != null) && auth.startsWith("Bearer");
            boolean haveAccessToken = request.getParameter("access_token") != null;
            return !haveOauth2Token && !haveAccessToken;
        }
    }
}
